-- demon_statue
-- create by cheny3
-- 魔神雕像

return {
    -- 判断
    canTrigger = function(args)
        -- 是否有魔神雕像格子
        for pos = 1, GRID_SIZE do
            local grid = DungeonM.getGridByPos(pos);
            if grid.type == GRID_TYPE_DEMON_STATUE
                and grid.state ~= GRID_STATE_DISABLE
                and grid:isOpened() then
                return true;
            end
        end
        return false;
    end,

    -- 触发
    trigger = function(args)
        -- 是否有魔神雕像格子
        local statueGrid;
        for pos = 1, GRID_SIZE do
            local grid = DungeonM.getGridByPos(pos);
            if grid.type == GRID_TYPE_DEMON_STATUE then
                statueGrid = grid;
                break;
            end
        end

        if not statueGrid then
            return false;
        end

        -- 获取玩家当前所有宝物
        local equips = EquipM.getUserTreasureList();

        -- 整理一下
        local splitLists = {};
        for classId, amount in pairs(equips) do
            -- 因为euqips包含装备的武器，所以这么处理
            if ItemM.getAmount(ME.user, classId) > 0
                and DemonStatueM.canSubmit(classId) then
                table.insert(splitLists, classId);
            end
        end

        local equips = {};
        local submitSuits = {};
        local step = args["step"];
        local layer = DungeonM.currentLayer();

        if step and layer % step == 0 then
            -- 献祭套装的层数
            local suits = SuitM.getAllSuits();
            for _, info in pairs(suits) do
                local items = info["active"];
                -- 需要是三件套装
                if #items == 3 then
                    local ok = true;
                    for _, classId in pairs(items) do
                        if not DemonStatueM.canSubmit(classId) then
                            ok = false;
                            break;
                        end
                    end
                    -- 判断能否献祭
                    if ok then
                        table.insert(submitSuits, items);
                    end
                end
            end

            if #submitSuits > 0 then
                -- 随机选一套装备
                equips = submitSuits[math.random(#submitSuits)];
                return DungeonActionM.go("sacrifice_demon", statueGrid:getPos(), 0, equips);
            end
        end

        -- 随机献祭1~3装备
        local num = math.random(1, 3);
        for i = 1, num do
            if #splitLists <= 0 then
                break;
            end
            local index = math.random(#splitLists);
            local classId = splitLists[index];
            table.insert(equips, classId);
            table.remove(splitLists, index);
        end

        return DungeonActionM.go("sacrifice_demon", statueGrid:getPos(), 0, equips);
    end,
};
